﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using EnterpriseFund.Common;
using DevExpress.Web.Mvc;
using DevExpress.Web.ASPxGridView;
using DevExpress.XtraReports.UI;

namespace EnterpriseFund.Controllers
{
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class QueryAllowanceForecastController : Controller
    {
        #region install

        private BLL.QueryAllowanceForecast _bll = new BLL.QueryAllowanceForecast();

        public decimal Year
        {
            get
            {
                return Convert.ToDecimal(OperateSession.get(Common.GlobalConstant.PARAM_SYSYEAR));
            }
        }
        public ActionResult Print()
        {


            // CreatReport(table);
            return View("Print");
        }
        public ActionResult ReportViewerPartial()
        {

            string fyear = OperateSession.get(Common.GlobalConstant.PARAM_SYSYEAR);
            DataTable newdt = new DataTable();
            BLL.TaxClassAllowance TaxClassAllowanceBLL = new BLL.TaxClassAllowance();
            List<Model.TaxClassAllowance> tl = TaxClassAllowanceBLL.GetModelList(" FYear=" + (decimal.Parse(fyear)));
            if (tl.Count > 0)
            {
                BLL.VSBZSXX VSBZSXXBLL = new BLL.VSBZSXX();
                DataSet ds = VSBZSXXBLL.GetDataforQueryAllowanceForecast((decimal.Parse(fyear)) + "-01-01", (decimal.Parse(fyear)) + "-12-31", (decimal.Parse(fyear)).ToString());
                BLL.TaxAuditAdjust TaxAuditAdjustBLL = new BLL.TaxAuditAdjust();
                DataSet yds = TaxAuditAdjustBLL.GetAllDateListByYear((decimal.Parse(fyear) - 1).ToString());
                DataTable dt = GetPolicyData(ds.Tables[0], yds.Tables[0], (decimal.Parse(fyear)).ToString());

                var nsrsbh = Request["nsrsbh"];
                var nsrbm = Request["nsrbm"];
                var nsrmc = Request["nsrmc"];
                var kbje1 = string.IsNullOrEmpty(Request["kbje1"]) ? decimal.MinValue : Convert.ToDecimal(Request["kbje1"]);
                var kbje2 = string.IsNullOrEmpty(Request["kbje2"]) ? decimal.MaxValue : Convert.ToDecimal(Request["kbje2"]);
                var FEnterprisePropNo = IsNull(DevExpress.Web.Mvc.ComboBoxExtension.GetValue<string>("FEnterprisePropNo"), Request["FEnterprisePropNo"]);
                var FTaxClassAllowanceNo = IsNull(DevExpress.Web.Mvc.ComboBoxExtension.GetValue<string>("FTaxClassAllowanceNo"), Request["FTaxClassAllowanceNo"]);

                ViewBag.nsrsbh = nsrsbh;
                ViewBag.nsrbm = nsrbm;
                ViewBag.nsrmc = nsrmc;
                ViewBag.kbje1 = Request["kbje1"];
                ViewBag.kbje2 = Request["kbje2"];
                ViewBag.FEnterprisePropNo = FEnterprisePropNo;
                ViewBag.FTaxClassAllowanceNo = FTaxClassAllowanceNo;

                var filter = "";
                if (!string.IsNullOrEmpty(nsrsbh)) filter = string.Format("nsrsbh = '{0}'", nsrsbh);
                else if (!string.IsNullOrEmpty(nsrbm)) filter = string.Format("nsrbm = '{0}'", nsrbm);
                else if (!string.IsNullOrEmpty(nsrmc)) filter = string.Format("nsrmc like '%{0}%'", nsrmc);

                if (kbje1 != decimal.MinValue || kbje2 != decimal.MaxValue)
                {
                    if (filter != "") filter += " and ";
                    filter += string.Format("FAllowanceAmount > {0} AND FAllowanceAmount < {1}", kbje1, kbje2);
                }

                if (!string.IsNullOrEmpty(FEnterprisePropNo))
                {
                    if (filter != "") filter += " and ";
                    filter += string.Format("FEnterprisePropNo = '{0}' ", FEnterprisePropNo);
                }

                if (!string.IsNullOrEmpty(FTaxClassAllowanceNo))
                {
                    if (filter != "") filter += " and ";
                    filter += string.Format("FTaxClassAllowanceNo = '{0}' ", FTaxClassAllowanceNo);
                }
                DataRow[] newdr = dt.Select(filter);
                if (newdr.Count() > 0)
                {
                    newdt = dt.Select(filter).CopyToDataTable();
                }
                else
                {
                    foreach (DataColumn dc in dt.Columns)
                    {
                        newdt.Columns.Add(dc.ColumnName);
                    }
                }
            }
            // var strWhere = GetWhereString();

            MVCReportGeneratonHelper generator = new MVCReportGeneratonHelper();
            generator.CustomizeColumnsCollection += new CustomizeColumnsCollectionEventHandler(generator_CustomizeColumnsCollection);
            generator.CustomizeColumn += new CustomizeColumnEventHandler(generator_CustomizeColumn);
            XtraReport report = generator.GenerateMVCReport(OperateSession.GetFromCache("QueryAllowanceForecast") as MVCxGridViewState, newdt);
            //  XtraReport report = generator.GenerateMVCReport(gridViewState, dt);

            //report.PaperKind = System.Drawing.Printing.PaperKind.A4;

            this.ViewData["rpt"] = report;

            return PartialView("ReportViewerPartial");

        }
        void generator_CustomizeColumnsCollection(object source, ColumnsCreationEventArgs e)
        {
            
            BLL.TaxClassAllowance tBLL = new BLL.TaxClassAllowance();
           
            for (int i = 0; i < e.ColumnsInfo.Count; i++)
            {

                if (e.ColumnsInfo[i].FieldName == "NSRSBH")
                {
                    e.ColumnsInfo[i].ColumnWidth = 170;
                }
                if (e.ColumnsInfo[i].FieldName == "NSRBM")
                {
                    e.ColumnsInfo[i].ColumnWidth = 100;
                }
                if (e.ColumnsInfo[i].FieldName == "NSRMC")
                {
                    e.ColumnsInfo[i].ColumnWidth = 320;

                }
                if (e.ColumnsInfo[i].FieldName == "FEnterprisePropName")
                {
                    e.ColumnsInfo[i].ColumnWidth = 100;
                }
                List<Model.TaxClassAllowance> tl = tBLL.GetModelList(" FYear=" + OperateSession.get(Common.GlobalConstant.PARAM_SYSYEAR));
                foreach (Model.TaxClassAllowance t in tl)
                {
                    if (e.ColumnsInfo[i].FieldName == t.FTaxClassAllowanceNo)
                    {
                        e.ColumnsInfo[i].ColumnWidth = 110;
                    }

                }

            }
        }
        void generator_CustomizeColumn(object source, ControlCustomizationEventArgs e)
        {

        }
        private string _strYearWhere;

        public QueryAllowanceForecastController()
        {
            _strYearWhere = "";
            InstallEnt();
            InstallTaxClassAllowance();
        }

        public DataTable TaxAllowance
        {
            get
            {
                //var cacheKey = "TaxAllowance" + Year;
                //var tax = HttpRuntime.Cache[cacheKey];
                //if (tax == null)
                //{
                //    tax = _bll.GetAllowanceForecast2(Year);
                //    HttpRuntime.Cache.Insert(cacheKey,tax,null,DateTime.MaxValue,TimeSpan.FromMinutes(20));
                //}
                //return tax as DataTable;
                return _bll.GetAllowanceForecast2(Year);
            }
        }

        // 当前年度企业性质
        public void InstallEnt()
        {
            var enterpriseProps = new BLL.EnterpriseProp().GetModelList(_strYearWhere);
            enterpriseProps.Insert(0, new Model.EnterpriseProp());
            ViewBag.EnterpriseProps = enterpriseProps;
        }

        // 当前年度可补贴税种
        public void InstallTaxClassAllowance()
        {
            var taxClassAllowance = new BLL.TaxClassAllowance().GetModelList(_strYearWhere);
            taxClassAllowance.Insert(0, new Model.TaxClassAllowance());
            ViewBag.TaxClassAllowance = taxClassAllowance;
        }

        #endregion

        private string IsNull(string s1, string s2)
        {
            return string.IsNullOrEmpty(s1) ? s2 : s1;
        }


        //public DataView Query()
        //{
        //    var nsrsbh = Request["nsrsbh"];
        //    var nsrbm = Request["nsrbm"];
        //    var nsrmc = Request["nsrmc"];
        //    var kbje1 = string.IsNullOrEmpty(Request["kbje1"]) ? decimal.MinValue : Convert.ToDecimal(Request["kbje1"]);
        //    var kbje2 = string.IsNullOrEmpty(Request["kbje2"]) ? decimal.MaxValue : Convert.ToDecimal(Request["kbje2"]);
        //    var FEnterprisePropNo = IsNull(DevExpress.Web.Mvc.ComboBoxExtension.GetValue<string>("FEnterprisePropNo"), Request["FEnterprisePropNo"]);
        //    var FTaxClassAllowanceNo = IsNull(DevExpress.Web.Mvc.ComboBoxExtension.GetValue<string>("FTaxClassAllowanceNo"), Request["FTaxClassAllowanceNo"]);

        //    ViewBag.nsrsbh = nsrsbh;
        //    ViewBag.nsrbm = nsrbm;
        //    ViewBag.nsrmc = nsrmc;
        //    ViewBag.kbje1 = Request["kbje1"];
        //    ViewBag.kbje2 = Request["kbje2"];
        //    ViewBag.FEnterprisePropNo = FEnterprisePropNo;
        //    ViewBag.FTaxClassAllowanceNo = FTaxClassAllowanceNo;

        //    var filter = "";
        //    if (!string.IsNullOrEmpty(nsrsbh)) filter = string.Format("nsrsbh = '{0}'", nsrsbh);
        //    else if (!string.IsNullOrEmpty(nsrbm)) filter = string.Format("nsrbm = '{0}'", nsrbm);
        //    else if (!string.IsNullOrEmpty(nsrmc)) filter = string.Format("nsrmc like '%{0}%'", nsrmc);

        //    if (kbje1 != decimal.MinValue || kbje2 != decimal.MaxValue)
        //    {
        //        if (filter != "") filter += " and ";
        //        filter += string.Format("FComputeValue > {0} AND FComputeValue < {1}", kbje1, kbje2);
        //    }

        //    if (!string.IsNullOrEmpty(FEnterprisePropNo))
        //    {
        //        if (filter != "") filter += " and ";
        //        filter += string.Format("FEnterprisePropNo = '{0}' ", FEnterprisePropNo);
        //    }

        //    if (!string.IsNullOrEmpty(FTaxClassAllowanceNo))
        //    {
        //        if (filter != "") filter += " and ";
        //        filter += string.Format("FTaxClassAllowanceNo = '{0}' ", FTaxClassAllowanceNo);
        //    }

        //    var view = new DataView(TaxAllowance);
        //    view.RowFilter = filter;
        //    //view.Sort = "FComputeValue DESC";
        //    return view;
        //}

        [AuthorityActionFilter("m_QueryAllowanceForecast", Order = 1)]
        [LogPageActionFilter("年度补贴预测", Order = 2)]
        public ActionResult Index()
        {
            string fyear = OperateSession.get(Common.GlobalConstant.PARAM_SYSYEAR);
            BLL.TaxClassAllowance TaxClassAllowanceBLL = new BLL.TaxClassAllowance();
            List<Model.TaxClassAllowance> tl = TaxClassAllowanceBLL.GetModelList(" FYear=" + (decimal.Parse(fyear)));
            if (tl.Count > 0)
            {
                ////var view = Query();
                //BLL.VSBZSXX VSBZSXXBLL = new BLL.VSBZSXX();
                //DataSet ds = VSBZSXXBLL.GetDataforQueryAllowanceForecast((decimal.Parse(fyear)) + "-01-01", (decimal.Parse(fyear)) + "-12-31", (decimal.Parse(fyear)).ToString());
                //BLL.TaxAuditAdjust TaxAuditAdjustBLL = new BLL.TaxAuditAdjust();
                //DataSet yds = TaxAuditAdjustBLL.GetAllDateListByYear((decimal.Parse(fyear) - 1).ToString());
                //DataTable dt = GetPolicyData(ds.Tables[0], yds.Tables[0], (decimal.Parse(fyear)).ToString());
               // return View(dt);
                return View();
            }
            else
            {
                ViewData["jsAlert"] = "请设置补贴类型！";
                DataTable dt = new DataTable();
                return View(dt);

            }

        }

        /// <summary>
        /// 数据格式转换装换为条件判断格式
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        public DataTable GetRuleExpressionDT(DataTable dt, string y)
        {
            var q = from nm in dt.AsEnumerable()
                    group nm by
                        new { key1 = nm.Field<decimal>("NSRDZDAH"), key2 = nm.Field<string>("NSRBM"), key3 = nm.Field<string>("NSRMC"), key4 = nm.Field<string>("NSRSBH") } into g
                    select new
                    {
                        NSRDZDAH = g.Key.key1,
                        NSRBM = g.Key.key2,
                        NSRMC = g.Key.key3,
                        NSRSBH = g.Key.key4
                    };

            BLL.TaxClassAllowance tBLL = new BLL.TaxClassAllowance();
            List<Model.TaxClassAllowance> tl = tBLL.GetModelList(" FYear=" + y);
            DataTable rDt = new DataTable();
            rDt.Columns.Add("NSRDZDAH");
            rDt.Columns.Add("NSRBM");
            rDt.Columns.Add("NSRMC");
            rDt.Columns.Add("NSRSBH");
            rDt.Columns.Add("FEnterprisePropNo");
            foreach (Model.TaxClassAllowance t in tl)
            {
                rDt.Columns.Add(t.FTaxClassAllowanceNo, typeof(decimal));
            }

            foreach (var n in q)
            {
                DataRow rDr = rDt.NewRow();
                DataRow[] nDr = dt.Select(" NSRDZDAH =" + n.NSRDZDAH.ToString());
                DataTable nDt = nDr.CopyToDataTable();
                foreach (DataColumn dc in rDt.Columns)
                {
                    DataRow[] dtrl = nDt.Select(" FTaxClassAllowanceNo='" + dc.ColumnName + "'");
                    if (dtrl.Count() > 0)
                    {
                        DataTable table = dtrl.CopyToDataTable();
                        rDr[dc.ColumnName] = table.Compute("Sum(se)", "true");
                    }
                    else
                    {
                        rDr[dc.ColumnName] = 0;
                    }

                }
                rDr["NSRDZDAH"] = n.NSRDZDAH.ToString();
                rDr["NSRBM"] = n.NSRBM.ToString();
                rDr["NSRMC"] = n.NSRMC.ToString();
                rDr["NSRSBH"] = n.NSRSBH.ToString();
                rDr["FEnterprisePropNo"] = nDr[0]["FEnterprisePropNo"];
                rDt.Rows.Add(rDr);
            }
            return rDt;
        }

        /// <summary>
        /// 公式判断数据格式
        /// </summary>
        /// <returns></returns>
        public DataTable GetComputeExpressionDT()
        {
            DataTable cDt = new DataTable();
            cDt.Columns.Add("se", typeof(decimal));
            cDt.Columns.Add("base", typeof(decimal));
            cDt.Columns.Add("rateIn", typeof(decimal));
            cDt.Columns.Add("rateOut", typeof(decimal));
            cDt.Columns.Add("zcjd");
            return cDt;
        }


        /// <summary>
        /// 政策鉴定过程
        /// </summary>
        /// <param name="dt">税款数据</param>
        /// <param name="yDt">上年度税款数据作为基数使用</param>
        /// <param name="y">年度</param>
        /// <returns>鉴定后数据列表</returns>
        public DataTable GetPolicyData(DataTable dt, DataTable yDt, string y)
        {
            DataTable sDt = new DataTable();
            sDt.Columns.Add("FAllowanceAmount", typeof(decimal));
            sDt.Columns.Add("FRuleFormula");
            sDt.Columns.Add("FComputeFormula");
            sDt.Columns.Add("FEnterprisePropName");
            sDt.Columns.Add("FTaxClassAllowanceName");
            sDt.Columns.Add("FTaxClassAllowanceNo");
            //dt.Columns.Add("FEnterprisePropNo");
            BLL.SupportPolicy sBLL = new BLL.SupportPolicy();

            List<Model.SupportPolicy> sl = sBLL.GetModelList(" sp.FYear=" + y);

            DataTable rDt = GetRuleExpressionDT(dt, y);///转换数据格式

            foreach (DataColumn dc in rDt.Columns)
            {
                sDt.Columns.Add(dc.ColumnName);
            }

            BLL.YGZAllowance YGZAllowanceBLL = new BLL.YGZAllowance();
            List<Model.YGZAllowance> YGZAllowanceList = YGZAllowanceBLL.GetModelList("FYear=" + OperateSession.get(GlobalConstant.PARAM_SYSYEAR));

            DataTable cDt = GetComputeExpressionDT();///获取公式判断数据格式

            foreach (Model.SupportPolicy s in sl)
            {
                s.FRuleExpression = s.FRuleExpression.Replace("&&", " and ");
                s.FRuleExpression = s.FRuleExpression.Replace("||", " or ");

                DataRow[] rdrl = rDt.Select(s.FRuleExpression);///条件匹配

                if (rdrl.Count() > 0)
                {
                    foreach (DataRow r in rdrl)
                    {
                        if (s.FEnterprisePropNo == r["FEnterprisePropNo"].ToString())
                        {
                            ///是否为普惠曾策
                            if (s.FProp == "1")
                            {
                                if (s.FTaxClassAllowanceName.Contains("营改增"))
                                {
                                    List<Model.YGZAllowance> newYGZAllowanceList = (from nm in YGZAllowanceList where nm.NSRDZDAH == decimal.Parse(r["NSRDZDAH"].ToString()) select nm).ToList();
                                    decimal sum = newYGZAllowanceList.Sum(z => z.FAmount);
                                    r[s.FTaxClassAllowanceNo] = decimal.Parse(r[s.FTaxClassAllowanceNo].ToString()) - sum;
                                }
                                DataRow[] yDrl = yDt.Select("FTaxClassAllowanceNo='" + s.FTaxClassAllowanceNo + "' and NSRDZDAH = '" + r["NSRDZDAH"] + "'");///查询上年度数据 做基数使用
                                DataRow cDr = cDt.NewRow();
                                if (s.FIsEvalBase == "Y")
                                {
                                    cDr["se"] = r[s.FTaxClassAllowanceNo];
                                    cDr["base"] = (yDrl.Count() > 0 ? yDrl[0]["FAdjustAmount"] : 0);
                                    cDr["rateIn"] = s.FInnerRate;
                                    cDr["rateOut"] = s.FOuterRate;
                                }
                                else
                                {
                                    cDr["se"] = r[s.FTaxClassAllowanceNo];
                                    cDr["base"] = 0;
                                    cDr["rateIn"] = 0;
                                    cDr["rateOut"] = s.FOuterRate;
                                }
                                if (cDr["base"] == null || cDr["base"].ToString() == "")
                                {
                                    cDr["base"] = "0";
                                }
                                cDt.Rows.Clear();
                                cDt.Rows.Add(cDr);
                                cDt.Columns["zcjd"].Expression = s.FComputeExpression;///公式计算补贴额

                                DataRow sDr = sDt.NewRow();
                                sDr["FAllowanceAmount"] = decimal.Round((decimal.Parse(cDt.Rows[0]["zcjd"].ToString()) / 10000), 0);
                                sDr["FRuleFormula"] = s.FRuleFormula;
                                sDr["FComputeFormula"] = s.FComputeDesc;
                                sDr["FEnterprisePropName"] = s.FEnterprisePropName;
                                sDr["FTaxClassAllowanceName"] = s.FTaxClassAllowanceName;
                                sDr["FTaxClassAllowanceNo"] = s.FTaxClassAllowanceNo;
                                foreach (DataColumn dc in rDt.Columns)
                                {
                                    sDr[dc.ColumnName] = r[dc.ColumnName];
                                }
                                sDt.Rows.Add(sDr);
                            }
                        }
                    }
                }
            }

            return sDt;
        }

        public ActionResult AllowanceForecastPartial()
        {
            string fyear = OperateSession.get(Common.GlobalConstant.PARAM_SYSYEAR);
            DataTable newdt = new DataTable();
            BLL.TaxClassAllowance TaxClassAllowanceBLL = new BLL.TaxClassAllowance();
            List<Model.TaxClassAllowance> tl = TaxClassAllowanceBLL.GetModelList(" FYear=" + (decimal.Parse(fyear)));
            if (tl.Count > 0)
            {
                BLL.VSBZSXX VSBZSXXBLL = new BLL.VSBZSXX();
                DataSet ds = VSBZSXXBLL.GetDataforQueryAllowanceForecast((decimal.Parse(fyear)) + "-01-01", (decimal.Parse(fyear)) + "-12-31", (decimal.Parse(fyear)).ToString());
                BLL.TaxAuditAdjust TaxAuditAdjustBLL = new BLL.TaxAuditAdjust();
                DataSet yds = TaxAuditAdjustBLL.GetAllDateListByYear((decimal.Parse(fyear) - 1).ToString());
                DataTable dt = GetPolicyData(ds.Tables[0], yds.Tables[0], (decimal.Parse(fyear)).ToString());

                var nsrsbh = Request["nsrsbh"];
                var nsrbm = Request["nsrbm"];
                var nsrmc = Request["nsrmc"];
                var kbje1 = string.IsNullOrEmpty(Request["kbje1"]) ? decimal.MinValue : Convert.ToDecimal(Request["kbje1"]);
                var kbje2 = string.IsNullOrEmpty(Request["kbje2"]) ? decimal.MaxValue : Convert.ToDecimal(Request["kbje2"]);
                var FEnterprisePropNo = IsNull(DevExpress.Web.Mvc.ComboBoxExtension.GetValue<string>("FEnterprisePropNo"), Request["FEnterprisePropNo"]);
                var FTaxClassAllowanceNo = IsNull(DevExpress.Web.Mvc.ComboBoxExtension.GetValue<string>("FTaxClassAllowanceNo"), Request["FTaxClassAllowanceNo"]);

                ViewBag.nsrsbh = nsrsbh;
                ViewBag.nsrbm = nsrbm;
                ViewBag.nsrmc = nsrmc;
                ViewBag.kbje1 = Request["kbje1"];
                ViewBag.kbje2 = Request["kbje2"];
                ViewBag.FEnterprisePropNo = FEnterprisePropNo;
                ViewBag.FTaxClassAllowanceNo = FTaxClassAllowanceNo;

                var filter = "";
                if (!string.IsNullOrEmpty(nsrsbh)) filter = string.Format("nsrsbh = '{0}'", nsrsbh);
                else if (!string.IsNullOrEmpty(nsrbm)) filter = string.Format("nsrbm = '{0}'", nsrbm);
                else if (!string.IsNullOrEmpty(nsrmc)) filter = string.Format("nsrmc like '%{0}%'", nsrmc);

                if (kbje1 != decimal.MinValue || kbje2 != decimal.MaxValue)
                {
                    if (filter != "") filter += " and ";
                    filter += string.Format("FAllowanceAmount > {0} AND FAllowanceAmount < {1}", kbje1, kbje2);
                }

                if (!string.IsNullOrEmpty(FEnterprisePropNo))
                {
                    if (filter != "") filter += " and ";
                    filter += string.Format("FEnterprisePropNo = '{0}' ", FEnterprisePropNo);
                }

                if (!string.IsNullOrEmpty(FTaxClassAllowanceNo))
                {
                    if (filter != "") filter += " and ";
                    filter += string.Format("FTaxClassAllowanceNo = '{0}' ", FTaxClassAllowanceNo);
                }
                DataRow[] newdr = dt.Select(filter);
                if (newdr.Count() > 0)
                {
                    newdt = dt.Select(filter).CopyToDataTable();
                }
                else
                {
                    foreach (DataColumn dc in dt.Columns)
                    {
                        newdt.Columns.Add(dc.ColumnName);
                    }
                }
            }
            return PartialView(newdt);
            //var view = Query();
            //return View(view);
        }

        #region 导出EXCEL

        public ActionResult ExportToXls()
        {
            //var table = Query();
            decimal fyear = decimal.Parse(OperateSession.get(Common.GlobalConstant.PARAM_SYSYEAR));
            BLL.VSBZSXX VSBZSXXBLL = new BLL.VSBZSXX();
            DataSet ds = VSBZSXXBLL.GetDataforQueryAllowanceForecast((fyear) + "-01-01", (fyear) + "-12-31", (fyear).ToString());
            BLL.TaxAuditAdjust TaxAuditAdjustBLL = new BLL.TaxAuditAdjust();
            DataSet yds = TaxAuditAdjustBLL.GetAllDateListByYear((fyear - 1).ToString());
            DataTable dt = GetPolicyData(ds.Tables[0], yds.Tables[0], (fyear).ToString());
            DataTable newdt = new DataTable();
            var filter = "";
            var nsrsbh = Fetch.Post("hnsrsbh");
            var nsrbm = Fetch.Post("hnsrbm");
            var nsrmc = Fetch.Post("hnsrmc");
            var kbje1 = Fetch.Post("hkbje1");
            var kbje2 = Fetch.Post("hkbje2");
            var FEnterprisePropNo = Fetch.Post("hFEnterprisePropNo");
            var FTaxClassAllowanceNo = Fetch.Post("htaxClassAllowanceNo");
            if (!string.IsNullOrEmpty(nsrsbh)) filter = string.Format("nsrsbh = '{0}'", nsrsbh);
            else if (!string.IsNullOrEmpty(nsrbm)) filter = string.Format("nsrbm = '{0}'", nsrbm);
            else if (!string.IsNullOrEmpty(nsrmc)) filter = string.Format("nsrmc like '%{0}%'", nsrmc);

            if (kbje1 != "" && kbje2 != "")
            {
                if (filter != "") filter += " and ";
                filter += string.Format("FAllowanceAmount > {0} AND FAllowanceAmount < {1}", kbje1, kbje2);
            }

            if (!string.IsNullOrEmpty(FEnterprisePropNo))
            {
                if (filter != "") filter += " and ";
                filter += string.Format("FEnterprisePropNo = '{0}' ", FEnterprisePropNo);
            }

            if (!string.IsNullOrEmpty(FTaxClassAllowanceNo))
            {
                if (filter != "") filter += " and ";
                filter += string.Format("FTaxClassAllowanceNo = '{0}' ", FTaxClassAllowanceNo);
            }
            DataRow[] newdr = dt.Select(filter);
            if (newdr.Count() > 0)
            {
                newdt = dt.Select(filter).CopyToDataTable();
            }
            else
            {
                foreach (DataColumn dc in dt.Columns)
                {
                    newdt.Columns.Add(dc.ColumnName);
                }
            }

            return GridViewExtension.ExportToXls(ExportGridViewSettings, newdt, HttpUtility.UrlEncode("年度补贴预测数据导出.xls"), true);
        }


        static GridViewSettings exportGridViewSettings;
        public static GridViewSettings ExportGridViewSettings
        {
            get
            {
                if (exportGridViewSettings == null)
                    exportGridViewSettings = CreateExportGridViewSettings();
                return exportGridViewSettings;
            }
        }

        public static GridViewSettings CreateExportGridViewSettings()
        {
            var ss = new GridViewSettings();
            ss.Name = "gvEditing";
            ss.KeyFieldName = "NSRDZDAH";
            ss.CallbackRouteValues = new { Controller = "QueryAllowanceForecast", Action = "AllowanceForecastPartial" };
            ss.Width = System.Web.UI.WebControls.Unit.Pixel(2000);
            ss.SettingsPager.PageSize = EnterpriseFund.Common.GlobalConstant.CONSTRING_PAGESIZE;
            //ss.Columns.Add("NSRDZDAH", "纳税人电子档案号");
            ss.Columns.Add("NSRSBH", "纳税人识别号");
            ss.Columns.Add("NSRBM", "纳税人编码");
            ss.Columns.Add("NSRMC", "企业名称");
            ss.Columns.Add("FEnterprisePropName", "企业性质");
            ss.SettingsExport.Styles.Header.BackColor = System.Drawing.Color.White;
            ss.SettingsExport.Styles.Header.ForeColor = System.Drawing.Color.Black;
            BLL.TaxClassAllowance tBLL = new BLL.TaxClassAllowance();
            List<Model.TaxClassAllowance> tl = tBLL.GetModelList(" FYear=" + OperateSession.get(Common.GlobalConstant.PARAM_SYSYEAR));
            foreach (Model.TaxClassAllowance t in tl)
            {
                ss.Columns.Add(t.FTaxClassAllowanceNo, t.FTaxClassAllowanceName).CellStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Right;
            }
            //ss.Columns.Add("FAmount", "营改增补助金额").PropertiesEdit.DisplayFormatString = "c"; 
            ss.Columns.Add("FTaxClassAllowanceName", "补贴税种名称").PropertiesEdit.DisplayFormatString = "c";
            ss.Columns.Add("FAllowanceAmount", "可补贴金额");
            ss.Columns.Add("FRuleFormula", "符合条件");
            ss.Columns.Add("FComputeFormula", "计算公式");

            ss.Settings.ShowGroupPanel = true;
            ss.Settings.ShowFooter = true;

            ss.SettingsLoadingPanel.Text = "数据读取中...";
            //ss.TotalSummary.Add(DevExpress.Data.SummaryItemType.Count, "NSRBM").DisplayFormat = "合计:￥{0}";
            ss.TotalSummary.Add(DevExpress.Data.SummaryItemType.Sum, "FAllowanceAmount").DisplayFormat = "合计:￥{0}";
            //ss.GroupSummary.Add(DevExpress.Data.SummaryItemType.Sum, "FAllowanceAmount").DisplayFormat = "合计:￥{0}";
            ss.SettingsBehavior.EnableCustomizationWindow = true;


            ss.ClientSideEvents.BeginCallback = "function(s,e){OnBeginCallback(s,e)}";
     
            ss.CommandColumn.Visible = false;

            ss.DataBinding = (sender, e) =>
            {
                ASPxGridView grid = (ASPxGridView)sender;
                for (int i = 0; i < grid.AllColumns.Count; i++)
                {
                    if (grid.AllColumns[i].HeaderStyle.HorizontalAlign == System.Web.UI.WebControls.HorizontalAlign.NotSet)
                    {
                        grid.AllColumns[i].HeaderStyle.HorizontalAlign = System.Web.UI.WebControls.HorizontalAlign.Center;
                    }
                }
            };
            ss.PreRender = ss.BeforeGetCallbackResult = (sender, e) =>
            {


                MVCxGridView gridView = sender as MVCxGridView;
                MVCxGridViewState gridViewState = new MVCxGridViewState(gridView);
                OperateSession.SetToCache(gridViewState, "QueryAllowanceForecast");


            };
            return ss;
        }

        #endregion

    }
}
